<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        type="success"
        icon="el-icon-download"
        @click="showGitHubSyncDialog"
      >
        同步 GitHub 仓库
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-refresh"
        @click="loadDirectories"
      >
        刷新目录
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="directories"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="网站目录" min-width="200">
        <template slot-scope="{row}">
          <div style="display: flex; align-items: center;">
            <i
              :class="getDirectoryIcon(row)"
              style="margin-right: 8px; font-size: 18px;"
              :style="{color: getDirectoryIconColor(row)}"
            />
            <span style="font-weight: 500;">{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="Git状态" width="180" align="center">
        <template slot-scope="{row}">
          <div>
            <el-tag
              :type="getGitStatusType(row.git_status)"
              size="small"
            >
              {{ getGitStatusText(row.git_status) }}
            </el-tag>
            <div v-if="row.behind_commits > 0 || row.ahead_commits > 0" style="font-size: 11px; color: #999; margin-top: 4px;">
              <span v-if="row.behind_commits > 0" style="color: #F56C6C;">
                ↓{{ row.behind_commits }}
              </span>
              <span v-if="row.ahead_commits > 0" style="color: #409EFF; margin-left: 4px;">
                ↑{{ row.ahead_commits }}
              </span>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="当前分支" width="120" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.current_branch" size="mini" type="info">
            <i class="el-icon-s-flag" /> {{ row.current_branch }}
          </el-tag>
          <span v-else style="color: #999;">-</span>
        </template>
      </el-table-column>

      <el-table-column label="远程仓库" min-width="300">
        <template slot-scope="{row}">
          <div v-if="row.remote_url" style="font-size: 12px;">
            <i class="el-icon-link" />
            <a :href="row.remote_url" target="_blank" style="color: #409EFF;">
              {{ row.remote_url }}
            </a>
          </div>
          <span v-else style="color: #999;">未配置</span>
        </template>
      </el-table-column>

      <el-table-column label="文件统计" width="150" align="center">
        <template slot-scope="{row}">
          <div style="font-size: 12px;">
            <div>{{ row.file_count }} 个文件</div>
            <div style="color: #999;">{{ formatSize(row.size) }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="预览链接" min-width="200">
        <template slot-scope="{row}">
          <div style="font-size: 12px;">
            <div style="margin-bottom: 5px;">
              <a
                :href="getPreviewUrl(row, 'local')"
                target="_blank"
                style="color: #409EFF;"
              >
                <i class="el-icon-link" /> 本地预览
              </a>
            </div>
            <div>
              <a
                :href="getPreviewUrl(row, 'production')"
                target="_blank"
                style="color: #67C23A;"
              >
                <i class="el-icon-link" /> 生产环境
              </a>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="280" fixed="right">
        <template slot-scope="{row}">
          <el-button
            v-if="row.is_git_repo"
            size="mini"
            type="success"
            icon="el-icon-download"
            @click="handlePull(row)"
          >
            拉取
          </el-button>
          <el-button
            v-if="row.is_git_repo"
            size="mini"
            type="primary"
            icon="el-icon-upload2"
            :disabled="!row.has_changes"
            @click="handleCommit(row)"
          >
            提交推送
          </el-button>
          <el-button
            size="mini"
            type="info"
            icon="el-icon-info"
            @click="handleViewDetails(row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Git 详情对话框 -->
    <el-dialog
      title="Git 状态详情"
      :visible.sync="detailDialogVisible"
      width="800px"
    >
      <div v-if="currentDirectory && gitDetails">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="目录名">
            {{ currentDirectory.name }}
          </el-descriptions-item>
          <el-descriptions-item label="是否Git仓库">
            <el-tag :type="gitDetails.is_git_repo ? 'success' : 'info'" size="small">
              {{ gitDetails.is_git_repo ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="gitDetails.is_git_repo" label="当前分支">
            <el-tag type="info" size="small">
              <i class="el-icon-s-flag" /> {{ gitDetails.current_branch }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="gitDetails.is_git_repo" label="远程仓库">
            <a :href="gitDetails.remote_url" target="_blank" style="color: #409EFF;">
              {{ gitDetails.remote_url || '未配置' }}
            </a>
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="gitDetails.is_git_repo" style="margin-top: 20px;">
          <el-divider content-position="left">最后一次提交</el-divider>
          <div v-if="gitDetails.last_commit && gitDetails.last_commit.sha">
            <p><strong>SHA:</strong> {{ gitDetails.last_commit.sha.substring(0, 8) }}</p>
            <p><strong>作者:</strong> {{ gitDetails.last_commit.author_name }} ({{ gitDetails.last_commit.author_email }})</p>
            <p><strong>时间:</strong> {{ gitDetails.last_commit.time_ago }}</p>
            <p><strong>信息:</strong> {{ gitDetails.last_commit.message }}</p>
          </div>
          <p v-else style="color: #999;">暂无提交记录</p>

          <el-divider content-position="left">未提交的更改</el-divider>
          <div v-if="gitDetails.has_changes">
            <div v-if="gitDetails.modified_files && gitDetails.modified_files.length > 0">
              <h4>已修改文件 ({{ gitDetails.modified_files.length }})</h4>
              <el-tag
                v-for="(file, index) in gitDetails.modified_files"
                :key="'m-' + index"
                size="small"
                style="margin: 2px;"
              >
                [{{ file.status }}] {{ file.file }}
              </el-tag>
            </div>
            <div v-if="gitDetails.untracked_files && gitDetails.untracked_files.length > 0" style="margin-top: 10px;">
              <h4>未跟踪文件 ({{ gitDetails.untracked_files.length }})</h4>
              <el-tag
                v-for="(file, index) in gitDetails.untracked_files"
                :key="'u-' + index"
                type="info"
                size="small"
                style="margin: 2px;"
              >
                {{ file }}
              </el-tag>
            </div>
          </div>
          <p v-else style="color: #67C23A;">
            <i class="el-icon-circle-check" /> 工作区干净，没有未提交的更改
          </p>
        </div>
      </div>
      <div v-else-if="currentDirectory">
        <el-alert
          title="该目录不是 Git 仓库"
          type="info"
          description="您可以手动在该目录中初始化 Git 仓库"
          show-icon
        />
      </div>
    </el-dialog>

    <!-- 提交对话框 -->
    <el-dialog
      title="提交并推送更改"
      :visible.sync="commitDialogVisible"
      width="600px"
    >
      <el-form label-width="100px">
        <el-form-item label="提交信息">
          <el-input
            v-model="commitMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入提交信息（必填）"
          />
        </el-form-item>
        <el-form-item label="推送到远程">
          <el-switch v-model="shouldPush" />
          <span style="margin-left: 10px; font-size: 12px; color: #999;">
            {{ shouldPush ? '提交后自动推送到远程仓库' : '仅在本地提交' }}
          </span>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="commitDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="committing"
          :disabled="!commitMessage"
          @click="executeCommit"
        >
          {{ committing ? '提交中...' : '确认提交' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- GitHub 同步对话框 -->
    <el-dialog
      title="同步 GitHub 仓库"
      :visible.sync="githubSyncDialogVisible"
      width="900px"
    >
      <div v-if="githubRepos.length > 0">
        <el-alert
          title="以下是 GitHub 上存在但本地还没有的仓库"
          type="info"
          :closable="false"
          style="margin-bottom: 15px;"
        />
        <el-table
          :data="githubRepos"
          border
          style="width: 100%"
        >
          <el-table-column label="仓库名称" min-width="200">
            <template slot-scope="{row}">
              <div><strong>{{ row.repo_name }}</strong></div>
              <div style="font-size: 12px; color: #999;">
                本地目录: {{ row.dir_name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="描述" min-width="200">
            <template slot-scope="{row}">
              <span style="font-size: 12px;">{{ row.description || '无描述' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.is_local" type="success" size="small">已同步</el-tag>
              <el-tag v-else type="info" size="small">未同步</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="最后更新" width="150">
            <template slot-scope="{row}">
              <span style="font-size: 12px;">{{ formatDate(row.updated_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="{row}">
              <el-button
                v-if="!row.is_local"
                size="mini"
                type="success"
                icon="el-icon-download"
                :loading="row.cloning"
                @click="handleCloneRepo(row)"
              >
                克隆
              </el-button>
              <el-tag v-else type="success" size="small">
                <i class="el-icon-check" /> 已存在
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else-if="loadingRepos">
        <div style="text-align: center; padding: 40px;">
          <i class="el-icon-loading" style="font-size: 32px;" />
          <p>正在加载 GitHub 仓库列表...</p>
        </div>
      </div>
      <div v-else>
        <el-alert
          title="未找到 GitHub 配置或仓库"
          type="warning"
          description="请先在 GitHub 配置页面添加配置"
          show-icon
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { scanDirectories, getGitStatus, gitCommitAndPush, gitPull, listGitHubRepos, cloneGitHubRepo } from '@/api/static_web_directory'

export default {
  name: 'SiteDirectories',
  data() {
    return {
      directories: [],
      listLoading: false,
      detailDialogVisible: false,
      commitDialogVisible: false,
      currentDirectory: null,
      gitDetails: null,
      commitMessage: '',
      shouldPush: true,
      committing: false,
      githubSyncDialogVisible: false,
      githubRepos: [],
      githubConfig: null,
      loadingRepos: false
    }
  },
  created() {
    this.loadDirectories()
  },
  methods: {
    loadDirectories() {
      this.listLoading = true
      scanDirectories().then(response => {
        this.listLoading = false
        if (response.success) {
          this.directories = response.data
        }
      }).catch(() => {
        this.listLoading = false
        this.$message.error('加载目录失败')
      })
    },
    handleViewDetails(row) {
      this.currentDirectory = row
      this.detailDialogVisible = true
      this.gitDetails = null

      if (row.is_git_repo) {
        // 加载详细的Git状态
        getGitStatus(row.name).then(response => {
          if (response.success) {
            this.gitDetails = response.data
          }
        }).catch(() => {
          this.$message.error('获取Git状态失败')
        })
      }
    },
    handlePull(row) {
      this.$confirm(
        `确定要从远程仓库拉取最新代码吗？\n\n如果本地有未提交的更改，系统会自动暂存。`,
        '拉取代码',
        {
          confirmButtonText: '确定拉取',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在拉取代码...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        gitPull(row.name).then(response => {
          loading.close()
          if (response.success) {
            this.$message.success('代码同步成功')
            this.loadDirectories()
          } else {
            this.$message.error(response.msg || '拉取失败')
          }
        }).catch(err => {
          loading.close()
          this.$message.error('拉取失败: ' + (err.message || '未知错误'))
        })
      })
    },
    handleCommit(row) {
      this.currentDirectory = row
      this.commitMessage = `Update ${row.name}`
      this.shouldPush = true
      this.commitDialogVisible = true
    },
    executeCommit() {
      if (!this.commitMessage) {
        this.$message.warning('请输入提交信息')
        return
      }

      this.committing = true

      const data = {
        commit_message: this.commitMessage,
        push: this.shouldPush
      }

      gitCommitAndPush(this.currentDirectory.name, data).then(response => {
        this.committing = false
        if (response.success) {
          const result = response.data
          if (result.committed) {
            this.$message.success(
              result.pushed ? '提交并推送成功' : '提交成功（未推送）'
            )
            this.commitDialogVisible = false
            this.loadDirectories()
          } else {
            this.$message.info('没有文件变更')
          }
        } else {
          this.$message.error(response.msg || '操作失败')
        }
      }).catch(err => {
        this.committing = false
        this.$message.error('操作失败: ' + (err.message || '未知错误'))
      })
    },
    getDirectoryIcon(row) {
      if (!row.is_git_repo) {
        return 'el-icon-folder'
      }
      if (row.has_changes) {
        return 'el-icon-folder-opened'
      }
      return 'el-icon-folder-checked'
    },
    getDirectoryIconColor(row) {
      if (!row.is_git_repo) {
        return '#909399'
      }
      if (row.has_changes) {
        return '#E6A23C'
      }
      return '#67C23A'
    },
    getGitStatusType(status) {
      const types = {
        'not_initialized': 'info',
        'synced': 'success',
        'has_changes': 'warning',
        'behind': 'danger',
        'ahead': 'primary'
      }
      return types[status] || 'info'
    },
    getGitStatusText(status) {
      const texts = {
        'not_initialized': '未初始化',
        'synced': '已同步',
        'has_changes': '有变更',
        'behind': '远程有更新',
        'ahead': '本地领先'
      }
      return texts[status] || status
    },
    formatSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
    },
    showGitHubSyncDialog() {
      this.githubSyncDialogVisible = true
      this.loadingRepos = true
      this.githubRepos = []

      listGitHubRepos().then(response => {
        this.loadingRepos = false
        if (response.success) {
          this.githubRepos = response.data.map(repo => ({
            ...repo,
            cloning: false
          }))
          this.githubConfig = response.config
        }
      }).catch(() => {
        this.loadingRepos = false
        this.$message.error('加载 GitHub 仓库失败')
      })
    },
    handleCloneRepo(row) {
      this.$confirm(
        `确定要克隆仓库 ${row.repo_name} 到本地目录 ${row.dir_name} 吗？`,
        '克隆仓库',
        {
          confirmButtonText: '确定克隆',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(() => {
        row.cloning = true

        const data = {
          config_id: this.githubConfig.id,
          repo_name: row.repo_name,
          dir_name: row.dir_name,
          owner: row.owner
        }

        cloneGitHubRepo(data).then(response => {
          row.cloning = false
          if (response.success) {
            this.$message.success('克隆成功')
            row.is_local = true
            this.loadDirectories()
          } else {
            this.$message.error(response.msg || '克隆失败')
          }
        }).catch(err => {
          row.cloning = false
          this.$message.error('克隆失败: ' + (err.message || '未知错误'))
        })
      }).catch(() => {
        // 取消操作
      })
    },
    formatDate(dateStr) {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))

      if (days === 0) return '今天'
      if (days === 1) return '昨天'
      if (days < 7) return `${days} 天前`
      if (days < 30) return `${Math.floor(days / 7)} 周前`
      if (days < 365) return `${Math.floor(days / 30)} 月前`
      return `${Math.floor(days / 365)} 年前`
    },
    getPreviewUrl(row, env) {
      // 生成预览链接
      // 本地环境: http://localhost:8000/static_sites/{domain}/index.html
      // 生产环境: https://tools.kikimami.com/static_sites/{domain}/index.html
      const domain = row.name // 目录名就是域名
      if (env === 'local') {
        return `${process.env.VUE_APP_BASE_API}/static_sites/${domain}/index.html`
      } else {
        // 生产环境URL
        return `https://tools.kikimami.com/static_sites/${domain}/index.html`
      }
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
</style>
